<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\AuthorizationRequest;
use Auth;

class AuthorizationsController extends Controller
{
    public function store(AuthorizationRequest $request)
    {

        $credentials['name'] = $request->name;

        $credentials['password'] = $request->password;

        if (!$token = \Auth::guard('api')->attempt($credentials)) {
            return $this->response->array([
                'status' => false,
                'data' =>[
                    'successflag' =>false
                ],
                'message' => '用户名或密码错误.',
            ])->setStatusCode(401);
        }

        return $this->respondWithToken($token)->setStatusCode(201);
    }

    public function update()
    {
        $token = Auth::guard('api')->refresh();
        return $this->respondWithToken($token)->setStatusCode(201);
    }

    public function destroy()
    {
        Auth::guard('api')->logout();

        return $this->response->array([
            'status'=>true,
            'data'=>[
                'successflag'=>true,
            ],
            'message'=>'退出登录成功',
        ])->setStatusCode(200);
    }

    protected function respondWithToken($token)
    {
        return $this->response->array([
            'status'=>true,
            'data'=>[
                'successflag' => true,
                'access_token' => $token,
                'expires_in' => \Auth::guard('api')->factory()->getTTL() * 60,
            ],
            'message'=>'登录成功'
        ]);
    }

}
